'use client'

import React, { useEffect, useState, useRef } from "react";
import {
    Button,
    Card,
    CardBody,
    CardHeader,
    Chip,
    Divider,
    Input,
    Modal,
    ModalBody,
    ModalContent,
    ModalFooter,
    ModalHeader,
    Spinner,
    Textarea,
    useDisclosure,
    Dropdown,
    DropdownTrigger,
    DropdownMenu,
    DropdownItem,
    ButtonGroup
} from "@nextui-org/react";
import { BiArrowBack, BiMessageSquare, BiHistory, BiTrash, BiRefresh, BiCopy, BiPencil, BiPlus, BiBot, BiStar, BiCheck, BiSend } from "react-icons/bi";
import { motion } from "framer-motion";
import { useRouter } from "next/navigation";
import ToastUtil from "@/app/utils/toastUtil";
import { AuthenticationChecker } from "@/app/config/authenticationChecker";
import { getAIHistory, getAIConversation, deleteAIConversation, createNote, chatWithAI, AIConversation, AIResponseDTO } from "@/app/service/AIService";
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import './globals.css';


// 固定的聊天会话ID
const FIXED_CHAT_ID = -1;

// 在页面顶部添加一个新的组件，用于包装ReactMarkdown
const MarkdownRenderer = ({ children }: { children: React.ReactNode }) => {
  return (
    <div className="markdown-content">
      <ReactMarkdown remarkPlugins={[remarkGfm]}>
        {children?.toString() || ''}
      </ReactMarkdown>
    </div>
  );
};

// 思考中的动画组件
const ThinkingAnimation = () => {
  const [dots, setDots] = useState('');
  
  useEffect(() => {
    const interval = setInterval(() => {
      setDots(prev => {
        if (prev === '...') return '';
        return prev + '.';
      });
    }, 500); // 每500毫秒变化一次
    
    return () => clearInterval(interval);
  }, []);
  
  return <span>思考中{dots}</span>;
};

// 添加在MarkdownRenderer旁边的打字机效果组件
const TypewriterEffect = ({ text, onComplete, scrollRef, scrollToBottom }: { 
  text: string, 
  onComplete?: () => void, 
  scrollRef?: React.RefObject<HTMLDivElement>,
  scrollToBottom?: () => void 
}) => {
  const [displayedText, setDisplayedText] = useState("");
  const [currentIndex, setCurrentIndex] = useState(0);
  
  useEffect(() => {
    if (currentIndex < text.length) {
      const timer = setTimeout(() => {
        setDisplayedText(prev => prev + text[currentIndex]);
        setCurrentIndex(prev => prev + 1);
        
        // 每次添加字符后滚动到底部
        if (scrollToBottom) {
          scrollToBottom();
        } else if (scrollRef && scrollRef.current) {
          scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
        }
      }, 5); // 打字速度，可以调整
      
      return () => clearTimeout(timer);
    } else if (onComplete) {
      onComplete();
    }
  }, [currentIndex, text, onComplete, scrollRef, scrollToBottom]);
  
  return (
    <MarkdownRenderer>
      {displayedText}
    </MarkdownRenderer>
  );
};

export default function AIAssistantPage() {
    const router = useRouter();
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    const [loading, setLoading] = useState(true);
    const [loadingText, setLoadingText] = useState("加载中...");

    // 历史记录相关状态
    const [history, setHistory] = useState<AIConversation[]>([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [totalItems, setTotalItems] = useState(0);
    const pageSize = 10;
    const [loadingHistory, setLoadingHistory] = useState(false);

    // 会话详情相关状态
    const [selectedConversation, setSelectedConversation] = useState<AIConversation | null>(null);
    const [conversationResponse, setConversationResponse] = useState<AIResponseDTO | null>(null);
    const [loadingConversation, setLoadingConversation] = useState(false);

    // 聊天相关状态
    const [chatMessages, setChatMessages] = useState<Array<{role: string, content: string}>>([]);
    const [chatInput, setChatInput] = useState("");
    const [chatLoading, setChatLoading] = useState(false);

    // 删除确认对话框
    const { isOpen: isDeleteModalOpen, onOpen: onOpenDeleteModal, onOpenChange: onDeleteModalChange } = useDisclosure();
    const [conversationToDelete, setConversationToDelete] = useState<number | null>(null);
    const [deleting, setDeleting] = useState(false);

    // 添加聊天容器引用
    const chatContainerRef = useRef<HTMLDivElement>(null);
    
    // 添加状态追踪正在打字的消息
    const [typingMessageIndex, setTypingMessageIndex] = useState<number | null>(null);
    
    // 添加思考中状态
    const [isThinking, setIsThinking] = useState(false);
    
    // 工具函数：滚动到底部
    const scrollToBottom = () => {
        if (chatContainerRef.current) {
            chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
        }
    };

    // 检查用户登录状态并初始化
    useEffect(() => {
        async function checkAuth() {
            setLoading(true);
            const [authenticated] = AuthenticationChecker();
            setIsLoggedIn(!!authenticated);

            if (!authenticated) {
                setLoadingText("请先登录");
                setTimeout(() => {
                    router.push('/');
                }, 1500);
            } else {
                await loadHistory();
                // 默认加载聊天模式
                setSelectedConversation({
                    id: FIXED_CHAT_ID,
                    userId: 0,
                    mode: "CHAT",
                    prompt: "聊天模式",
                    response: "",
                    createdAt: new Date().toISOString()
                });
                setConversationResponse(null);
                
                // 初始化时加载聊天历史记录
                await loadChatHistory();
            }
            setLoading(false);
        }

        checkAuth();
    }, []);

    // 加载历史记录
    const loadHistory = async () => {
        try {
            setLoadingHistory(true);
            const response = await getAIHistory(currentPage - 1, pageSize);
            if (response) {
                // 过滤掉CHAT类型的记录，因为我们将使用固定的聊天模式
                const filteredHistory = response.records?.filter(item => item.mode !== "CHAT") || [];
                setHistory(filteredHistory);
                
                // 计算非CHAT类型记录的总数
                // 方法1：使用当前页过滤后的数量来近似（不精确但简单）
                setTotalItems(filteredHistory.length);
                
                // 方法2：如果后端返回了所有记录，可以通过请求全部记录然后过滤来获得准确总数
                // 但这种方式会增加额外的API调用，只在需要精确分页时使用
            }
        } catch (error) {
            console.error("加载历史记录失败:", error);
            ToastUtil("获取历史记录失败", "❌", "error");
        } finally {
            setLoadingHistory(false);
        }
    };

    // 页码变化时重新加载历史
    useEffect(() => {
        if (isLoggedIn) {
            loadHistory();
        }
    }, [currentPage, isLoggedIn]);

    // 加载聊天历史
    const loadChatHistory = async () => {
        try {
            setChatLoading(true);
            const response = await getAIHistory(0, 100); // 获取较多记录以确保加载所有聊天
            
            if (response && response.records) {
                // 仅筛选CHAT类型的记录
                const chatRecords = response.records.filter(item => item.mode === "CHAT") || [];
                
                // 如果有聊天记录，构建聊天消息数组
                if (chatRecords.length > 0) {
                    // 按时间从早到晚排序
                    chatRecords.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
                    
                    // 构建聊天消息
                    let messages: Array<{role: string, content: string}> = [];
                    for (let record of chatRecords) {
                        // 添加用户消息
                        messages.push({ role: "user", content: record.prompt });
                        
                        // 从response字段中提取AI回复
                        if (record.response) {
                            try {
                                const responseObj = JSON.parse(record.response);
                                if (responseObj.choices && responseObj.choices.length > 0 && 
                                    responseObj.choices[0].message && responseObj.choices[0].message.content) {
                                    
                                    const aiContent = responseObj.choices[0].message.content;
                                    messages.push({ role: "assistant", content: aiContent });
                                }
                            } catch (e) {
                                console.error("解析聊天记录失败:", e);
                            }
                        }
                    }
                    
                    // 更新聊天消息
                    setChatMessages(messages);
                    
                    // 设置最后一条AI消息为已完成状态
                    setTypingMessageIndex(null);
                    
                    // 消息加载完成后滚动到底部
                    setTimeout(scrollToBottom, 100);
                }
            }
        } catch (error) {
            console.error("加载聊天历史失败:", error);
            ToastUtil("获取聊天历史失败", "❌", "error");
        } finally {
            setChatLoading(false);
        }
    };

    // 清空所有聊天记录
    const clearChatHistory = async () => {
        try {
            setChatLoading(true);
            
            // 先获取所有聊天记录
            const response = await getAIHistory(0, 100);
            
            if (response && response.records) {
                // 筛选CHAT类型的记录
                const chatRecords = response.records.filter(item => item.mode === "CHAT") || [];
                
                // 逐个删除聊天记录
                let deletePromises: Promise<boolean>[] = [];
                for (let record of chatRecords) {
                    deletePromises.push(deleteAIConversation(record.id));
                }
                
                // 等待所有删除操作完成
                await Promise.all(deletePromises);
                
                // 清空本地聊天消息
                setChatMessages([]);
                
                ToastUtil("聊天记录已清空", "✅", "success");
            }
        } catch (error) {
            console.error("清空聊天历史失败:", error);
            ToastUtil("清空聊天历史失败", "❌", "error");
        } finally {
            setChatLoading(false);
        }
    };

    // 加载会话详情
    const loadConversationDetail = async (conversationId: number) => {
        // 如果是固定的聊天会话，需要加载聊天历史
        if (conversationId === FIXED_CHAT_ID) {
            setSelectedConversation({
                id: FIXED_CHAT_ID,
                userId: 0,
                mode: "CHAT",
                prompt: "聊天模式",
                response: "",
                createdAt: new Date().toISOString()
            });
            setConversationResponse(null);
            
            // 加载聊天历史
            await loadChatHistory();
            return;
        }

        try {
            setLoadingConversation(true);
            const conversation = await getAIConversation(conversationId);
            setSelectedConversation(conversation);

            // 解析响应
            if (conversation.response) {
                try {
                    // 解析外层response
                    const responseObj = JSON.parse(conversation.response);
                    
                    // 提取choice和message
                    if (responseObj.choices && responseObj.choices.length > 0 && 
                        responseObj.choices[0].message && responseObj.choices[0].message.content) {
                        
                        const content = responseObj.choices[0].message.content;
                        
                        // 尝试解析content，它可能是一个JSON字符串
                        try {
                            const parsedContent = JSON.parse(content);
                            setConversationResponse(parsedContent);
                        } catch (e) {
                            // 如果content不是有效的JSON，则直接使用它
                            setConversationResponse({
                                content: content
                            });
                        }
                    } else {
                        setConversationResponse(null);
                    }
                } catch (e) {
                    console.error("解析响应失败:", e);
                    setConversationResponse(null);
                }
            } else {
                setConversationResponse(null);
            }
        } catch (error) {
            console.error("加载会话详情失败:", error);
            ToastUtil("获取会话详情失败", "❌", "error");
        } finally {
            setLoadingConversation(false);
        }
    };

    // 删除会话
    const handleDeleteConversation = async () => {
        if (!conversationToDelete) return;

        try {
            setDeleting(true);
            const success = await deleteAIConversation(conversationToDelete);

            if (success) {
                ToastUtil("删除成功", "✅", "success");

                // 如果当前正在查看被删除的会话，则切换到聊天模式
                if (selectedConversation?.id === conversationToDelete) {
                    setSelectedConversation({
                        id: FIXED_CHAT_ID,
                        userId: 0,
                        mode: "CHAT",
                        prompt: "聊天模式",
                        response: "",
                        createdAt: new Date().toISOString()
                    });
                    setConversationResponse(null);
                }

                // 重新加载历史
                await loadHistory();
            } else {
                ToastUtil("删除失败", "❌", "error");
            }
        } catch (error) {
            console.error("删除会话失败:", error);
            ToastUtil("删除会话失败", "❌", "error");
        } finally {
            setDeleting(false);
            onDeleteModalChange(false);
        }
    };

    // 打开删除确认对话框
    const openDeleteDialog = (conversationId: number) => {
        // 不能删除固定的聊天会话
        if (conversationId === FIXED_CHAT_ID) return;

        setConversationToDelete(conversationId);
        onOpenDeleteModal();
    };

    // 修改发送聊天消息的实现，添加思考中状态
    const sendChatMessage = async () => {
        if (!chatInput.trim()) {
            return;
        }

        try {
            setChatLoading(true);

            // 添加用户消息到聊天记录
            const newUserMessage = { role: "user", content: chatInput };
            // 临时更新，包含思考中状态
            const updatedMessagesWithThinking = [
                ...chatMessages, 
                newUserMessage,
                // 添加"思考中"临时消息
                { role: "assistant", content: "思考中..." }
            ];
            setChatMessages(updatedMessagesWithThinking);
            setChatInput("");
            setIsThinking(true);
            
            // 立即滚动到底部显示用户消息和思考状态
            scrollToBottom();

            // 调用AI聊天API
            const response = await chatWithAI([...chatMessages, newUserMessage]);

            // 收到AI回复后，替换"思考中"消息
            if (response && response.content) {
                // 移除临时的"思考中"消息，添加真实回复
                const finalMessages = [
                    ...chatMessages, 
                    newUserMessage,
                    { role: "assistant", content: response.content }
                ];
                setChatMessages(finalMessages);
                setIsThinking(false);
                
                // 确保先滚动到底部再开始打字效果
                scrollToBottom();
                
                // 设置最后一条消息为正在打字状态
                setTimeout(() => {
                    setTypingMessageIndex(finalMessages.length - 1);
                    // 再次滚动确保位置正确
                    scrollToBottom();
                }, 50);
            } else {
                // 如果没有有效回复，移除"思考中"消息
                setChatMessages([...chatMessages, newUserMessage]);
                setIsThinking(false);
                ToastUtil("AI未返回有效回复", "❌", "error");
            }
        } catch (error) {
            console.error("发送聊天消息失败:", error);
            // 出错时移除"思考中"消息
            setChatMessages([...chatMessages, { role: "user", content: chatInput }]);
            setIsThinking(false);
            ToastUtil("聊天消息发送失败", "❌", "error");
        } finally {
            setChatLoading(false);
        }
    };

    // 在页面加载后添加滚动到底部的操作
    useEffect(() => {
        // 检查是否在聊天模式并且有消息
        if (selectedConversation?.id === FIXED_CHAT_ID && chatMessages.length > 0) {
            scrollToBottom();
        }
    }, [selectedConversation, chatMessages]);

    // 如果正在加载，显示加载状态
    if (loading) {
        return (
            <div className="flex h-screen items-center justify-center bg-white dark:bg-default-100">
                <div className="text-center">
                    <Spinner size="lg" color="primary" />
                    <p className="mt-2 text-gray-500">{loadingText}</p>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-white dark:bg-default-100 p-4">
            <div className="max-w-7xl mx-auto h-[calc(100vh-2rem)]">
                {/* 页面标题和返回按钮 */}
                <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-3">
                        <Button
                            isIconOnly
                            variant="light"
                            onClick={() => router.push('/')}
                        >
                            <BiArrowBack className="text-xl" />
                        </Button>
                        <div className="flex items-center gap-2">
                            <BiBot className="text-3xl text-primary" />
                            <h1 className="text-2xl font-bold">AI助手</h1>
                        </div>
                    </div>
                </div>

                {/* 主内容区 - 左右分栏布局，高度充满屏幕 */}
                <div className="grid grid-cols-1 lg:grid-cols-10 gap-4 h-[calc(100%-4rem)]">
                    {/* 左侧历史记录 - 占30% */}
                    <Card shadow="sm" className="lg:col-span-3 h-full overflow-hidden">
                        <CardHeader className="flex justify-between items-center">
                            <div className="flex items-center gap-2">
                                <BiHistory className="text-primary text-xl" />
                                <h2 className="text-xl font-semibold">历史记录</h2>
                            </div>
                            <Button
                                variant="light"
                                isIconOnly
                                onClick={loadHistory}
                                isLoading={loadingHistory}
                            >
                                <BiRefresh className="text-lg" />
                            </Button>
                        </CardHeader>
                        <Divider />
                        <CardBody className="p-0 overflow-hidden">
                            <div className="max-h-[calc(100%-4rem)] overflow-auto pr-2 p-2">
                                {/* 固定的聊天模式Item */}
                                <Card
                                    shadow="none"
                                    className={`border cursor-pointer mb-2 w-full ${selectedConversation?.id === FIXED_CHAT_ID ? 'border-primary border-2' : 'border-gray-200 dark:border-gray-700'}`}
                                    isPressable
                                    onPress={() => loadConversationDetail(FIXED_CHAT_ID)}
                                >
                                    <CardBody className="p-3">
                                        <div className="flex justify-between items-start">
                                            <div className="flex items-start gap-2 w-full overflow-hidden">
                                                <div className="flex-shrink-0 w-8 h-8 rounded-full bg-primary-100 text-primary flex items-center justify-center">
                                                    <BiMessageSquare className="text-lg" />
                                                </div>
                                                <div className="flex-1 min-w-0 overflow-hidden">
                                                    <p className="font-medium line-clamp-1 text-sm">聊天模式</p>
                                                    <div className="flex items-center gap-1 mt-1 w-full">
                                                        <Chip size="sm" variant="flat" color="primary" className="text-xs px-1 py-0 h-5">CHAT</Chip>
                                                        <p className="text-xs text-gray-500">与AI进行对话</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </CardBody>
                                </Card>

                                {/* 历史记录 */}
                                {loadingHistory ? (
                                    <div className="flex justify-center py-4">
                                        <Spinner size="sm" color="primary" />
                                    </div>
                                ) : history.length === 0 ? (
                                    <div className="flex flex-col items-center py-4">
                                        <p className="text-gray-500 text-sm">暂无其他历史记录</p>
                                    </div>
                                ) : (
                                    history.map((item) => (
                                        <Card
                                            key={item.id}
                                            shadow="none"
                                            className={`border cursor-pointer mb-2 w-full ${selectedConversation?.id === item.id ? 'border-primary border-2' : 'border-gray-200 dark:border-gray-700'}`}
                                            isPressable
                                            onPress={() => loadConversationDetail(item.id)}
                                        >
                                            <CardBody className="p-3">
                                                <div className="flex justify-between items-start">
                                                    <div className="flex items-start gap-2 w-full overflow-hidden">
                                                        <div className="flex-shrink-0 w-8 h-8 rounded-full bg-primary-100 text-primary flex items-center justify-center">
                                                            <BiBot className="text-lg" />
                                                        </div>
                                                        <div className="flex-1 min-w-0 overflow-hidden">
                                                            <p className="font-medium line-clamp-1 text-sm">{item.prompt}</p>
                                                            <div className="flex items-center gap-1 mt-1 w-full">
                                                                <Chip size="sm" variant="flat" color="primary" className="text-xs px-1 py-0 h-5">{item.mode}</Chip>
                                                                <p className="text-xs text-gray-500 whitespace-nowrap overflow-hidden text-ellipsis">
                                                                    {new Date(item.createdAt).toLocaleString()}
                                                                </p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <Button
                                                        isIconOnly
                                                        size="sm"
                                                        variant="light"
                                                        color="danger"
                                                        className="ml-1 flex-shrink-0"
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            openDeleteDialog(item.id);
                                                        }}
                                                    >
                                                        <BiTrash />
                                                    </Button>
                                                </div>
                                            </CardBody>
                                        </Card>
                                    ))
                                )}
                            </div>

                            {/* 分页 */}
                            {totalItems > pageSize && (
                                <div className="flex justify-center p-2 border-t">
                                    <ButtonGroup size="sm">
                                        <Button
                                            disabled={currentPage === 1 || loadingHistory}
                                            onClick={() => setCurrentPage(currentPage - 1)}
                                            variant="flat"
                                        >
                                            上一页
                                        </Button>
                                        <Button variant="flat" disabled>
                                            {currentPage} / {Math.ceil(totalItems / pageSize)}
                                        </Button>
                                        <Button
                                            disabled={currentPage >= Math.ceil(totalItems / pageSize) || loadingHistory}
                                            onClick={() => setCurrentPage(currentPage + 1)}
                                            variant="flat"
                                        >
                                            下一页
                                        </Button>
                                    </ButtonGroup>
                                </div>
                            )}
                        </CardBody>
                    </Card>

                    {/* 右侧聊天/详情区域 - 占70% */}
                    <Card shadow="sm" className="lg:col-span-7 h-full overflow-hidden">
                        <CardHeader className="flex justify-between">
                            <h2 className="text-xl font-semibold">
                                {selectedConversation?.id === FIXED_CHAT_ID ? '聊天' : '对话详情'}
                            </h2>
                            {selectedConversation && selectedConversation.id !== FIXED_CHAT_ID && (
                                <Chip
                                    color="primary"
                                    variant="flat"
                                >
                                    {selectedConversation.mode}
                                </Chip>
                            )}
                        </CardHeader>
                        <Divider />
                        <CardBody className="p-0 overflow-hidden">
                            {loadingConversation ? (
                                <div className="flex justify-center py-8">
                                    <Spinner size="md" color="primary" />
                                </div>
                            ) : selectedConversation?.id === FIXED_CHAT_ID ? (
                                // 显示聊天界面
                                <div className="flex flex-col h-full">
                                    <div className="flex items-center justify-between p-3 border-b bg-gray-50 dark:bg-gray-900">
                                        <div className="flex items-center">
                                            <BiMessageSquare className="text-primary mr-2" />
                                            <span className="font-medium">聊天模式</span>
                                        </div>
                                        {chatMessages.length > 0 && (
                                            <Button
                                                size="sm"
                                                color="danger"
                                                variant="light"
                                                startContent={<BiTrash />}
                                                onClick={clearChatHistory}
                                                isDisabled={chatLoading}
                                            >
                                                清空聊天记录
                                            </Button>
                                        )}
                                    </div>
                                    <div className="flex-1 p-4 overflow-auto" ref={chatContainerRef}>
                                        {chatMessages.length === 0 ? (
                                            <div className="h-full flex flex-col items-center justify-center">
                                                <BiBot className="text-6xl text-gray-300 mb-4" />
                                                <p className="text-gray-500 mb-1">AI助手已准备好</p>
                                                <p className="text-gray-400 text-sm">开始聊天吧</p>
                                            </div>
                                        ) : (
                                            <div className="space-y-4">
                                                {chatMessages.map((msg, index) => (
                                                    <motion.div
                                                        key={index}
                                                        className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
                                                        initial={{ opacity: 0, y: 10 }}
                                                        animate={{ opacity: 1, y: 0 }}
                                                        transition={{ duration: 0.3 }}
                                                    >
                                                        {msg.role === 'assistant' && (
                                                            <div className="w-8 h-8 rounded-full bg-primary-100 text-primary flex items-center justify-center mr-2 flex-shrink-0">
                                                                <BiBot className="text-lg" />
                                                            </div>
                                                        )}
                                                        <div
                                                            className={`max-w-[80%] p-3 ${msg.role === 'user'
                                                                    ? 'bg-primary text-white rounded-2xl rounded-tr-none shadow-sm'
                                                                    : 'bg-gray-100 dark:bg-gray-800 rounded-2xl rounded-tl-none shadow-sm'
                                                                }`}
                                                        >
                                                            {msg.role === 'user' ? (
                                                                <p className="whitespace-pre-wrap">{msg.content}</p>
                                                            ) : (
                                                                msg.content === "思考中..." ? (
                                                                    <ThinkingAnimation />
                                                                ) : typingMessageIndex === index ? (
                                                                    <TypewriterEffect 
                                                                        text={msg.content} 
                                                                        onComplete={() => setTypingMessageIndex(null)} 
                                                                        scrollRef={chatContainerRef}
                                                                        scrollToBottom={scrollToBottom}
                                                                    />
                                                                ) : (
                                                                    <MarkdownRenderer>
                                                                        {msg.content}
                                                                    </MarkdownRenderer>
                                                                )
                                                            )}
                                                        </div>
                                                        {msg.role === 'user' && (
                                                            <div className="w-8 h-8 rounded-full bg-primary flex items-center justify-center ml-2 flex-shrink-0">
                                                                <span className="text-white text-sm">我</span>
                                                            </div>
                                                        )}
                                                    </motion.div>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                    <div className="p-4 border-t bg-gray-50 dark:bg-gray-900">
                                        <div className="flex items-center gap-2">
                                            <Textarea
                                                placeholder="输入消息..."
                                                value={chatInput}
                                                onValueChange={setChatInput}
                                                minRows={1}
                                                maxRows={5}
                                                className="flex-1"
                                                disabled={chatLoading}
                                                onKeyDown={(e) => {
                                                    if (e.key === 'Enter' && !e.shiftKey) {
                                                        e.preventDefault();
                                                        sendChatMessage();
                                                    }
                                                }}
                                            />
                                            <Button
                                                isIconOnly
                                                color="primary"
                                                isLoading={chatLoading}
                                                onClick={sendChatMessage}
                                                isDisabled={!chatInput.trim() || chatLoading}
                                                className="rounded-full h-10 w-10 flex items-center justify-center"
                                            >
                                                {!chatLoading && <BiSend />}
                                            </Button>
                                        </div>
                                    </div>
                                </div>
                            ) : (
                                // 显示已选择的对话详情
                                <div className="p-4 h-full overflow-auto">
                                    {renderResponseByMode(selectedConversation.mode, conversationResponse, router)}
                                </div>
                            )}
                        </CardBody>
                    </Card>
                </div>

                {/* 删除确认对话框 */}
                <Modal
                    isOpen={isDeleteModalOpen}
                    onOpenChange={onDeleteModalChange}
                    backdrop="blur"
                >
                    <ModalContent>
                        {(onClose) => (
                            <>
                                <ModalHeader className="flex flex-col gap-1">
                                    确认删除
                                </ModalHeader>
                                <ModalBody>
                                    <p>确定要删除这条会话记录吗？此操作不可撤销。</p>
                                </ModalBody>
                                <ModalFooter>
                                    <Button color="default" variant="flat" onPress={onClose} disabled={deleting}>
                                        取消
                                    </Button>
                                    <Button color="danger" onPress={handleDeleteConversation} isLoading={deleting}>
                                        删除
                                    </Button>
                                </ModalFooter>
                            </>
                        )}
                    </ModalContent>
                </Modal>
            </div>
        </div>
    );
}

// 根据模式渲染不同类型的响应
const renderResponseByMode = (mode: string, response: AIResponseDTO | null, router) => {
    if (!response) return (
        <div className="flex flex-col items-center justify-center h-full">
            <p className="text-gray-500">未找到详细信息</p>
        </div>
    );

    switch (mode) {
        case "CREATE_NOTE":
            return (
                <div>
                    <h3 className="text-md font-medium mb-2">AI响应</h3>
                    <div className="border rounded-lg p-4 bg-gray-50 dark:bg-gray-900">
                        {response.title && (
                            <div className="mb-4">
                                <h4 className="text-sm text-gray-500 mb-1">标题</h4>
                                <p className="p-2 bg-white dark:bg-gray-800 rounded">
                                    {response.title}
                                </p>
                            </div>
                        )}

                        {response.content && (
                            <div className="mb-4">
                                <div className="flex justify-between items-center mb-2">
                                    <h4 className="text-sm text-gray-500">内容</h4>
                                    <Button
                                        size="sm"
                                        variant="flat"
                                        color="primary"
                                        startContent={<BiCopy />}
                                        className="ml-2"
                                        onPress={() => {
                                            navigator.clipboard.writeText(response.content || "");
                                            ToastUtil("已复制到剪贴板", "✅", "success");
                                        }}
                                        isDisabled={!response.content}
                                    >
                                        复制
                                    </Button>
                                </div>
                                <div className="p-2 bg-white dark:bg-gray-800 rounded max-h-[400px] overflow-auto">
                                    <MarkdownRenderer>
                                        {response.content}
                                    </MarkdownRenderer>
                                </div>
                            </div>
                        )}

                        {response.suggestedTags && response.suggestedTags.length > 0 && (
                            <div className="mb-4">
                                <h4 className="text-sm text-gray-500 mb-1">推荐标签</h4>
                                <div className="flex flex-wrap gap-2 mt-1">
                                    {response.suggestedTags.map((tag, index) => (
                                        <Chip
                                            key={index}
                                            variant="flat"
                                            color="primary"
                                            size="sm"
                                        >
                                            {tag}
                                        </Chip>
                                    ))}
                                </div>
                            </div>
                        )}

                        <div className="mt-4 pt-3 border-t flex justify-end">
                            <Button
                                color="primary"
                                startContent={<BiPencil />}
                                className="px-4"
                                onPress={() => {
                                    // 创建新笔记时，我们将前往笔记创建页面，并填充AI生成的内容
                                    localStorage.setItem('aiGeneratedContent', response.content || "");
                                    localStorage.setItem('aiGeneratedTitle', response.title || "AI生成笔记");
                                    router.push('/note/new?fromAI=true');
                                }}
                            >
                                创建笔记
                            </Button>
                        </div>
                    </div>
                </div>
            );

        case "TECHNICAL_TUTORIAL":
            let sections = [];
            let codeExamples = [];

            try {
                if (response.structuredData) {
                    const data = JSON.parse(response.structuredData);
                    sections = data.sections || [];
                    codeExamples = data.codeExamples || [];
                }
            } catch (e) {
                console.error("解析结构化数据失败", e);
            }

            return (
                <div>
                    <h3 className="text-md font-medium mb-2">技术教程</h3>
                    <div className="border rounded-lg p-4 bg-gray-50 dark:bg-gray-900">
                        {response.title && (
                            <div className="mb-4">
                                <h4 className="text-sm text-gray-500 mb-1">标题</h4>
                                <p className="p-2 bg-white dark:bg-gray-800 rounded font-medium">
                                    {response.title}
                                </p>
                            </div>
                        )}

                        {response.content && (
                            <div className="mb-4">
                                <h4 className="text-sm text-gray-500 mb-1">简介</h4>
                                <div className="p-2 bg-white dark:bg-gray-800 rounded">
                                    <MarkdownRenderer>
                                        {response.content}
                                    </MarkdownRenderer>
                                </div>
                            </div>
                        )}

                        {sections.length > 0 && (
                            <div className="mb-4">
                                <h4 className="text-sm text-gray-500 mb-1">章节</h4>
                                <div className="space-y-3">
                                    {sections.map((section, index) => (
                                        <div key={index} className="p-2 bg-white dark:bg-gray-800 rounded">
                                            <h5 className="font-medium">{section.title}</h5>
                                            <MarkdownRenderer>
                                                {section.content}
                                            </MarkdownRenderer>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        {codeExamples.length > 0 && (
                            <div className="mb-4">
                                <h4 className="text-sm text-gray-500 mb-1">代码示例</h4>
                                <div className="space-y-3">
                                    {codeExamples.map((example, index) => (
                                        <div key={index} className="p-2 bg-white dark:bg-gray-800 rounded">
                                            <div className="flex justify-between">
                                                <h5 className="font-medium">{example.language} - {example.description}</h5>
                                                <Button
                                                    size="sm"
                                                    variant="flat"
                                                    color="primary"
                                                    startContent={<BiCopy />}
                                                    onPress={() => {
                                                        navigator.clipboard.writeText(example.code || "");
                                                        ToastUtil("已复制到剪贴板", "✅", "success");
                                                    }}
                                                >
                                                    复制
                                                </Button>
                                            </div>
                                            <pre className="text-sm mt-1 p-2 bg-gray-100 dark:bg-gray-900 rounded overflow-auto">
                                                <code>{example.code}</code>
                                            </pre>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        {response.suggestedTags && response.suggestedTags.length > 0 && (
                            <div className="mt-4">
                                <h4 className="text-sm text-gray-500 mb-1">推荐标签</h4>
                                <div className="flex flex-wrap gap-2 mt-1">
                                    {response.suggestedTags.map((tag, index) => (
                                        <Chip
                                            key={index}
                                            variant="flat"
                                            color="primary"
                                            size="sm"
                                        >
                                            {tag}
                                        </Chip>
                                    ))}
                                </div>
                            </div>
                        )}

                        <div className="mt-6 flex justify-end">
                            <Button
                                color="primary"
                                startContent={<BiPencil />}
                                onPress={() => {
                                    localStorage.setItem('aiGeneratedContent', response.content || "");
                                    localStorage.setItem('aiGeneratedTitle', response.title || "技术教程");
                                    router.push('/note/new?fromAI=true');
                                }}
                            >
                                创建笔记
                            </Button>
                        </div>
                    </div>
                </div>
            );

        case "SUMMARIZE":
            // 直接从response中提取结构化数据
            let summary = '';
            let keyPoints = [];

            try {
                // 首先检查是否有structuredData属性
                if (response.structuredData) {
                    const data = JSON.parse(response.structuredData);
                    summary = data.summary || '';
                    keyPoints = data.keyPoints || [];
                } 
                // 如果没有structuredData但有内容，则使用内容
                else if (response.content) {
                    summary = response.content;
                }
                // 如果既没有structuredData也没有content，可能需要尝试解析原始响应
                else if (response.summary) {
                    summary = response.summary;
                    keyPoints = response.keyPoints || [];
                }
                
                // 记录一下调试信息
                console.log("SUMMARIZE模式数据:", response);
            } catch (e) {
                console.error("解析摘要数据失败", e);
                summary = response.content || "无法解析摘要内容";
            }

            return (
                <div>
                    <h3 className="text-md font-medium mb-2">摘要</h3>
                    <div className="border rounded-lg p-4 bg-gray-50 dark:bg-gray-900">
                        <div className="mb-4">
                            <h4 className="text-sm text-gray-500 mb-1">摘要内容</h4>
                            <div className="p-2 bg-white dark:bg-gray-800 rounded">
                                <MarkdownRenderer>
                                    {summary}
                                </MarkdownRenderer>
                            </div>
                        </div>

                        {keyPoints && keyPoints.length > 0 && (
                            <div>
                                <h4 className="text-sm text-gray-500 mb-1">关键点</h4>
                                <ul className="list-disc pl-5 p-2 bg-white dark:bg-gray-800 rounded">
                                    {keyPoints.map((point, index) => (
                                        <li key={index} className="text-sm mb-1">{point}</li>
                                    ))}
                                </ul>
                            </div>
                        )}
                    </div>
                </div>
            );

        default:
            return (
                <div>
                    <h3 className="text-md font-medium mb-2">AI响应</h3>
                    <div className="border rounded-lg p-4 bg-gray-50 dark:bg-gray-900">
                        {response.content && (
                            <div>
                                <div className="flex justify-between">
                                    <h4 className="text-sm text-gray-500 mb-1">内容</h4>
                                    <Button
                                        size="sm"
                                        variant="flat"
                                        color="primary"
                                        startContent={<BiCopy />}
                                        onPress={() => {
                                            navigator.clipboard.writeText(response.content || "");
                                            ToastUtil("已复制到剪贴板", "✅", "success");
                                        }}
                                        isDisabled={!response.content}
                                    >
                                        复制
                                    </Button>
                                </div>
                                <div className="p-2 bg-white dark:bg-gray-800 rounded max-h-[400px] overflow-auto">
                                    <MarkdownRenderer>
                                        {response.content}
                                    </MarkdownRenderer>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            );
    }
}; 